# coding=utf-8


import sys
import os
import ConfigParser
import xlrd
from ItemModel import *
from ServiceModel import  *
from SheetModel import *
from ClassModel import *
from jinja2 import Environment, PackageLoader

# 设置编码
reload(sys)
sys.setdefaultencoding('utf-8')

# 读取配置文件
cf = ConfigParser.ConfigParser()
cf.read("config.conf")
filename = cf.get("save_dir", "excel_path")
version = cf.get("save_dir", "version")
xml_save_dir = cf.get("save_dir", "xml_save_path")
json_save_dir = cf.get("save_dir", "json_save_path")
service_codes = cf.get("save_dir", "service_codes")

# Overview对应字段
overview_service_code = cf.get("constant_text", "overview_service_code")
overview_service_name = cf.get("constant_text", "overview_service_name")
overview_remark = cf.get("constant_text", "overview_remark")
overview_version = cf.get("constant_text", "overview_version")
overview_operation = cf.get("constant_text", "overview_operation")
#end

#服务号对应字段
name_string = cf.get("constant_text", "name_string")
short_name_string = cf.get("constant_text", "short_name_string")
type_string = cf.get("constant_text", "type_string")
metadata_string = cf.get("constant_text", "metadata_string")
length_string = cf.get("constant_text", "length_string")
required_string = cf.get("constant_text", "required_string")
range_string = cf.get("constant_text", "range_string")
version_string = cf.get("constant_text", "version_string")
remark_string = cf.get("constant_text", "remark_string")
#end
sheetIndexModel = SheetModel()

xl_workbook = xlrd.open_workbook(filename)


def get_service_models():
    init_overview_index()
    services = []
    sheet = xl_workbook.sheet_by_name('Overview')

    last_service_model = ServiceModel()
    print '本次生成的服务列表:' 
    for row_index in range(0, sheet.nrows):
        row_obj = sheet.row(row_index)
        if row_index == 0:
            continue
        elif str(row_obj[sheetIndexModel.overview_service_code_index].value) != '':
            service_model = ServiceModel()
            service_model.service_code = row_obj[sheetIndexModel.overview_service_code_index].value
            service_model.name = row_obj[sheetIndexModel.overview_service_name_index].value
            service_model.description = row_obj[sheetIndexModel.overview_remark_index].value
            # 只有版本号匹配的才能加入
            if len(service_codes) > 0:
                if service_model.service_code in service_codes:
                    if service_model.service_code != last_service_model.service_code:
                        print row_obj[sheetIndexModel.overview_service_code_index].value
                        services.append(service_model)
            else:
                if service_model.service_code != last_service_model.service_code:
                    print row_obj[sheetIndexModel.overview_service_code_index].value
                    services.append(service_model)
            last_service_model = service_model
    print '=============================================' 
    return services


def init_overview_index():
    sheet = xl_workbook.sheet_by_name('Overview')
    row_zero = sheet.row(0)
    for col in range(0, sheet.ncols):
        cell = row_zero[col]
        if overview_service_code.lower() == cell.value.lower():
            sheetIndexModel.overview_service_code_index = col
        elif overview_service_name.lower() == cell.value.lower():
            sheetIndexModel.overview_service_name_index = col
        elif overview_remark.lower() == cell.value.lower():
            sheetIndexModel.overview_remark_index = col
        elif overview_version.lower() == cell.value.lower():
            sheetIndexModel.overview_version_index = col
        elif overview_operation.lower() == cell.value.lower():
            sheetIndexModel.overview_operation_index = col


def init_index(sheet, first_row_num):
    row_zero = sheet.row(first_row_num)

    for col in range(0, sheet.ncols):
        cell = row_zero[col]
        if name_string.lower() == cell.value.lower():
            sheetIndexModel.nameIndex = col
        elif short_name_string.lower() == cell.value.lower():
            sheetIndexModel.shotNameIndex = col
        elif length_string.lower() == cell.value.lower():
            sheetIndexModel.lengthIndex = col
        elif type_string.lower() == cell.value.lower():
            sheetIndexModel.typeIndex = col
        elif metadata_string.lower() == cell.value.lower():
            sheetIndexModel.metadataIndex = col
        elif required_string.lower() == cell.value.lower():
            sheetIndexModel.requiredIndex = col
        elif range_string.lower() == cell.value.lower():
            sheetIndexModel.rangeIndex = col
        elif version_string.lower() == cell.value.lower():
            sheetIndexModel.versionIndex = col
        elif remark_string.lower() == cell.value.lower():
            sheetIndexModel.remarkIndex = col

    return sheetIndexModel


def get_item_model(sheet, row_num, name_index, item_index):
    sheet_model = sheetIndexModel
    item_model = ItemModel()
    item_model.index = item_index

    name = sheet.cell(row_num, name_index)
    item_model.name = name.value

    short_name = sheet.cell(row_num, sheet_model.shotNameIndex)
    item_model.short_name = short_name.value

    item_type = sheet.cell(row_num, sheet_model.typeIndex)
    item_model.item_type = item_type.value

    metadata = sheet.cell(row_num, sheet_model.metadataIndex)
    item_model.metadata = metadata.value

    length = sheet.cell(row_num, sheet_model.lengthIndex)
    item_model.length = length.value
    if item_model.length == '':
        item_model.length = '0'

    required = sheet.cell(row_num, sheet_model.requiredIndex)
    item_model.required = required.value

    range_value = sheet.cell(row_num, sheet_model.rangeIndex)
    item_model.range_value = range_value.value

    version_cell = sheet.cell(row_num, sheet_model.versionIndex)
    item_model.version = version_cell.value

    remark = sheet.cell(row_num, sheet_model.remarkIndex)
    item_model.remark = remark.value

    return item_model


def get_model_index(sheet, row_num, model, name_index, parent_model):
    row_index = row_num+1
    if row_index < sheet.nrows:
        temp_model = get_item_model(sheet, row_index, name_index, 0)
        if temp_model.name != "":
            return row_index

    model_name_index = name_index + 1
    item_index = 0
    while row_index < sheet.nrows:
        item_model = get_item_model(sheet, row_index, model_name_index, item_index)
        item_index = item_index + 1
        if item_model.name == "":
            return row_index
        else:
            model.items.append(item_model)
            if item_model.is_model() and (model_name_index+1) != sheetIndexModel.shotNameIndex:

                row_index = get_model_index(sheet, row_index, item_model, model_name_index, model)
            else:
                row_index = row_index + 1
    return row_index


def write_data_to_xml(model, xml_name):
    print '正在生成xml文件:'+xml_name
    env = Environment(loader=PackageLoader('ParseExcelCoreApi', '../templates'))
    template = env.get_template('service.xml')
    xml = template.render(service_model=model)
    if not os.path.exists(xml_save_dir):
        os.makedirs(xml_save_dir)
    with open(xml_save_dir+xml_name+'.xml', 'w') as f:
        f.write(xml)

def write_data_to_json(model, xml_name):
    print '正在生成json文件:'+xml_name
    env = Environment(loader=PackageLoader('ParseExcelCoreApi', '../templates'))
    template = env.get_template('service.json')
    json = template.render(service_model=model)
    if not os.path.exists(json_save_dir):
        os.makedirs(json_save_dir)
    with open(json_save_dir+xml_name+'.json', 'w') as f:
        f.write(json)

def parse_sheets():
    services = get_service_models()
    print '%s版本改动的服务个数:%s' % (version, len(services))
    for service_model in services:
        sheet = xl_workbook.sheet_by_name(service_model.service_code)
        xml_name = sheet.name
        if xml_name != 'Overview':
            first_row_num = 0
            sheetIndexModel = init_index(sheet, first_row_num)
            # 构造填充Service Model
            class_model = None
            row_num = first_row_num + 1

            while row_num < sheet.nrows:
                cell = sheet.cell(row_num, 0)
                # 构造Request和Response
                if cell.value:
                    item_index = 0
                    class_model = ClassModel()
                    if service_model.request_model is None:
                        class_model.class_type = 'Request'
                        class_model.name = cell.value
                        service_model.request_model = class_model
                    else:
                        class_model.class_type = 'Response'
                        class_model.name = cell.value
                        service_model.response_model = class_model
                item_model = get_item_model(sheet, row_num, sheetIndexModel.nameIndex, item_index)
                class_model.items.append(item_model)
                item_index += 1
                if item_model.is_model():
                    row_num = get_model_index(sheet, row_num, item_model, sheetIndexModel.nameIndex, class_model)
                    # print row_num

                else:
                    row_num = row_num + 1

            write_data_to_xml(service_model, xml_name)
            write_data_to_json(service_model, xml_name)


if __name__ == '__main__':
    parse_sheets()
